﻿using System;
using System.Collections.Generic;
using System.Linq;
using Citi.Import.Util;
using Citi.ResourceConsolidation.Domain.Utils;

namespace Citi.ResourceConsolidation.Domain
{
    public partial class BusinessContact
    {
        private const string BusinessContactIdColumn = "Business Contact ID";
        private const string BusinessContactNameColumn = "Business Contact Name";

        public static readonly List<Definition<BusinessContact>> Definitions = new List<Definition<BusinessContact>>
            {
                new Definition<BusinessContact> { ModelProperty = x => x.Code, MaxLength = 50, Required = true, ColumnName = BusinessContactIdColumn, CustomConversionMethod = ValidateCode},
                new Definition<BusinessContact> { ModelProperty = x => x.Description, MaxLength = 300, Required = true, ColumnName = BusinessContactNameColumn},
            };

        private static object ValidateCode(ref BusinessContact model, string value, List<string> fields, ref string error, List<string> headers = null)
        {
            if (String.IsNullOrEmpty(value))
            {
                error = String.Format("The field {0} can not be null", BusinessContactIdColumn);
                return Conversion.Validation.Failed;
            }

            var domain = CacheFacade.Get(new BusinessContact().SelectAll<BusinessContact>).FirstOrDefault(x => x.Code == value);

            if (domain != null)
            {
                model = domain;
                return Conversion.Validation.Validated;
            }

            return value;
        }

        public static void Save(List<BusinessContact> contacts)
        {
            contacts = contacts.Distinct(new BusinessContactComparer()).Where(x => x != null && !String.IsNullOrEmpty(x.Code) && x.Id == 0).ToList();

            if (!contacts.Any()) return;
            contacts.First().Save(contacts, 100);

            CacheFacade.Clear(typeof(BusinessContact));
            Context.ClearContext();
        }
    }

    public class BusinessContactComparer : IEqualityComparer<BusinessContact>
    {
        public bool Equals(BusinessContact x, BusinessContact y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
                return false;

            return x.Description == y.Description && x.Id == y.Id && x.Code == y.Code;
        }

        public int GetHashCode(BusinessContact item)
        {
            if (ReferenceEquals(item, null)) return 0;

            int hashDescription = item.Description == null ? 0 : item.Description.GetHashCode();
            int hashId = item.Description == null ? 0 : item.Id.GetHashCode();
            int hashCode = item.Code == null ? 0 : item.Code.GetHashCode();

            return hashDescription ^ hashId ^ hashCode;
        }
    }
}
